package com.wyw.leetcode.learning.medium;

import java.util.ArrayList;
import java.util.List;

/**
 * leetcode topic 179
 * 最大数
 *
 * @Author Mr Wu （yewen.wu.china@gmail.com）
 * @Date 2022/7/6 10:59
 */
public class Topic179 {
    public static void main(String[] args) {
//        int[] nums = new int[] {10,2};
//        System.out.println(largestNumber(nums));
        int[] nums = new int[] {3,30,34,5,9};
        System.out.println(largestNumber(nums));

    }

    //暴力破解
    public static String largestNumber(int[] nums) {
        int size = nums.length;
        int maxLength = 0;// 字符串最大长度
        for(int i: nums) {
            maxLength = findMaxLength(i, maxLength);
        }
        String[] numsString = new String[size];
        List<Object[]> list = new ArrayList();
        for(int i = 0; i< size; i++) {
            numsString[i] = maxNumber(nums[i], maxLength);
            list.add(new Object[]{numsString[i], i});
        }
        // 注意不能用asList()得到的集合去增删了
//        List<String> list = Arrays.asList(numsString);

        int[] numsIndex = new int[size];
        for(int i = 0; i< size; i++) {
            findIndexArray(numsIndex, list, i);
        }

        String result = "";
        for(int i: numsIndex) {
            result = result.concat(String.valueOf(nums[i]));
        }
        return result;
    }

    static int[] findIndexArray(int[] numsIndex, List<Object[]> list, int indexResult) {
        int maxValue = 0;
        int nowListIndex = 0;
        int index = 0;
        int size =list.size();
        for(int i = 0; i< size; i++) {
            Object[] objects = list.get(i);
            int temp = Integer.parseInt(objects[0].toString());
            if(temp > maxValue) {
                maxValue = temp;
                nowListIndex = i;
                index = Integer.parseInt(objects[1].toString());
            }
        }
        list.remove(nowListIndex);
        numsIndex[indexResult] = index;
        return numsIndex;
    }

    static String maxNumber(int a, int maxLength) {
        String aStr = String.valueOf(a);
        for(int i = aStr.length(); i<maxLength; i++) {
            aStr = aStr.concat("9");
        }
        return aStr;
    }

    static int findMaxLength(int a, int maxLength) {
        int length = String.valueOf(a).length();
        if(length > maxLength) {
            return length;
        }
        return maxLength;
    }
}
